package chen.bupt.mapreduce.recordnumber;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import chen.bupt.mapreduce.segterm.SegTermJob;
import chen.bupt.util.HDFSFileUtils;

/**
 * 统计记录条数的MR Job
 * @author forrest
 *
 */
public class RecordNumJob {
	private static String inputPath = "/user/chenlingpeng/smthdata_seg";
	private static String outputPath = "/user/chenlingpeng/smth/recordnum";

	public static class Map extends
			Mapper<LongWritable, Text, Text, IntWritable> {
		private static Text text = new Text("1");
		private static IntWritable one = new IntWritable(1);

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			if(!HDFSFileUtils.isInputFile(context))
				return;;

			context.write(text, one);
		}
	}

	public static class Reduce extends
			Reducer<Text, IntWritable, Text, IntWritable> {
		private static Text text = new Text("total line");

		public void reduce(Text key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();
			}
			context.write(text, new IntWritable(sum));
		}
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "getRecordNum");
		job.setJarByClass(SegTermJob.class);
		job.setMapperClass(Map.class);
		job.setCombinerClass(Reducer.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		Path input = new Path(inputPath);
		Path output = new Path(outputPath);
		HDFSFileUtils.deleteFile(output, conf);
		FileInputFormat.addInputPath(job, input);
		FileOutputFormat.setOutputPath(job, output);
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	
	}

}
